package com.anglireports.report.response.util;

import com.alibaba.fastjson.JSONObject;
import com.anglireports.report.response.result.ReportsResult;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 简单Http请求工具类
 * @author lvjilei
 * @ceateTime 2019/3/25.
 */
public class HttpSendRequest {

    /**
     * 发送get请求
     * @param url
     * @param params
     * @return
     */
    public static JSONObject doGet(String url, Map<String,Object> params){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet;
        if ( null == params){
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + HttpSendRequest.generateParamString(params));
        }
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null){
                String json = EntityUtils.toString(entity, "UTF-8").trim();
                return JSONObject.parseObject(json);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String generateParamString(Map<String,Object> params){
        StringBuffer paramString = new StringBuffer();
        Iterator<String> iter = params.keySet().iterator();

        while (iter.hasNext()){
            String key = iter.next();
            paramString.append(key).append("=").append(params.get(key));
            if (iter.hasNext()){
                paramString.append("&");
            }
        }
        return paramString.toString();
    }


    public static void main(String[] args){
        HashMap<String, Object> map =
                new HashMap<String, Object>();
        map.put("starttime", "2019-01-27T09:47:43.498Z");
        map.put("endtime", "2019-03-01T09:47:43.498Z");

        JSONObject result = HttpSendRequest.doGet("http://poc1.emotibot.com:3254/emotiedu/reports", map);
        ReportsResult reportsResult = JSONObject.toJavaObject(result, ReportsResult.class);
        System.out.println("attention=" + reportsResult.getReports().get(0).getConcentration().getAttention());
    }

}
